package com.jukte.recipe;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import com.ewhat.recipes.R;
import com.jukte.recipe.db.DataBaseManager;
import com.jukte.recipe.utils.Constants;
import com.jukte.recipe.utils.FTPDownloadUtil;
import com.jukte.recipe.webservices.CheckDataTask;
import com.jukte.recipe.webservices.GetDataTask;

public class SplashActivity extends Activity {// used to know if the back button was pressed in the splash screen activity and avoid opening the next activity
    private boolean mIsBackButtonPressed;
    private static final int SPLASH_DURATION = 2000; // 2 seconds
    private Context con;
    private boolean splashOK = false, downloadOK = false;
    private ProgressDialog pd;
    private int serverVersion = 0;
    private SharedPreferences prefs;
    private Editor edt;
 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash_screen);
        con=SplashActivity.this;
        DataBaseManager.init(con);
        Handler handler = new Handler();
        
        prefs = getSharedPreferences("QUINOA", MODE_PRIVATE);
        edt = prefs.edit();
        
        pd = new ProgressDialog(SplashActivity.this);
		pd.setCancelable(false);
		pd.setMessage("Loading...");
        
 
        if(Constants.isNetworkConnected(this)){
        	new CheckDataTask(con, pd){
        		@Override
        		public void onNoData() {
        			downloadOK = true;
        			gotoMainPage();
        		}
        		
        		@Override
        		public void onHasData(String version) {
        			serverVersion = Integer.parseInt(version);
        			
        			new GetDataTask(con, pd){
        				
        				@Override
        				public void onSuccess(String res) {
        					if(!res.equals("OK")) finish();
        					else{
        						new DownloadTask().execute();
        					}
        				}
        			}.execute();
        			
        		}
        	}.execute();
        	
        	
        	// run a thread after 2 seconds to start the home screen
            handler.postDelayed(new Runnable() {
     
                @Override
                public void run() {
                	splashOK = true;
                    // make sure we close the splash screen so the user won't come back when it presses back key
     
                	gotoMainPage();
                     
                }
     
            }, SPLASH_DURATION); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
     
        }else{
        	if(prefs.getInt("VERSION", 0) == 0){
	        	new AlertDialog.Builder(this)
	        		.setTitle("Notice")
	        		.setMessage("Application missing data!\nPlease connect to internet to get it.")
	        		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							finish();
						}
					})
					.show();
        	}else{
        		downloadOK = true;
        		
        		// run a thread after 2 seconds to start the home screen
                handler.postDelayed(new Runnable() {
         
                    @Override
                    public void run() {
                    	splashOK = true;
                        // make sure we close the splash screen so the user won't come back when it presses back key
         
                    	gotoMainPage();
                         
                    }
         
                }, SPLASH_DURATION); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
         
        	}
        }
        
    }
    
    private void gotoMainPage(){
    	if(splashOK && downloadOK){
    		if(pd.isShowing()) pd.dismiss();
    		
    		if(serverVersion>0){
	    		edt.putInt("VERSION", serverVersion);
	    		edt.commit();
    		}
    		
	    	finish();
	        
	        if (!mIsBackButtonPressed) {
	        	Intent intent = new Intent(SplashActivity.this, HomeTabActivity.class);
	            SplashActivity.this.startActivity(intent);
	       }
    	}
    }
    
    public class DownloadTask extends AsyncTask<Void, Void, Void>{
    	private String server = "ftp.tahminaghani.com";
        private int port = 21;
        private String user = "angel";
        private String pass = "5E3aZqdllL9o";
        private FTPClient ftpClient;
        private FTPDownloadUtil ftpUtil;
        private String remoteDirPath = "";
        private String saveDirPath = "";
        private int downloaded = 0, total = 0;
        private int percentage = 0;
        
    	@Override
    	protected void onPreExecute() {
    		if(!pd.isShowing()) pd.show();
    		
    		ftpClient = new FTPClient();
    		ftpUtil = new FTPDownloadUtil();
    	}
    	
		@Override
		protected Void doInBackground(Void... arg0) {
			
			try {
				// connect and login to the server
                ftpClient.connect(server, port);
                ftpClient.login(user, pass);
     
                // use local passive mode to pass firewall
                ftpClient.enterLocalPassiveMode();
     
                Log.i("DOWNLOAD", "Connected");
     
                remoteDirPath = "/www/quinoa/raw/";
                saveDirPath = SplashActivity.this.getFilesDir().getPath()+"/raw/";
                new File(saveDirPath).mkdirs();
                
                FTPFile[] subFiles = ftpUtil.downloadDirectory(ftpClient, remoteDirPath, "", saveDirPath);
				
				// log out and disconnect from the server
	            ftpClient.logout();
	            ftpClient.disconnect();
	            
	            
	            if(null != subFiles){
	            	total = subFiles.length;
	            	
	            	for (FTPFile aFile : subFiles) {
	    	        	String currentFileName = aFile.getName();
	    	            if (currentFileName.equals(".") || currentFileName.equals("..")) {
	    	                // skip parent directory and the directory itself
	    	                continue;
	    	            }
	    	            
	    	            String newDirPath = saveDirPath + currentFileName;
	    	            File f = new File(newDirPath);
	    	        	if(f.exists()){
	    	        		downloaded++;
	        				publishProgress();
	    	        		continue;
	    	        	}
	    	        	URL imageUrl = new URL("http://tahminaghani.com/quinoa/raw/"+currentFileName);
	    	    		URLConnection ucon = imageUrl.openConnection();

	    	        	byte buffer[] = new byte[8*1024];
	    	        	InputStream reader = new BufferedInputStream(ucon.getInputStream());
	    	            FileOutputStream output= new FileOutputStream(newDirPath);
	    	            
	    	            int readByte = 0;
	    	            synchronized (buffer) {
	    	                while ((readByte = reader.read(buffer)) != -1) {
	    	                	output.write(buffer,0,readByte);
	    	                }
	    	                output.flush();
	    	    			output.close();
	    	    			reader.close();
	    	            }
	    	        	
	    	            downloaded++;
	    				publishProgress();
	    	            Log.i("DOWNLOAD", "DOWNLOADED the file: " + currentFileName + "=>"+new File(newDirPath).exists());
	    	        }
	            }
	            
			} catch (IOException e) {
				e.printStackTrace();
			}
            
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Void... vs) {
			percentage = (int)(((float)downloaded/total) * 100);
			percentage += 1;
			pd.setMessage("Loading("+percentage+"%)...");
		}
    	
		@Override
		protected void onPostExecute(Void result) {
			Log.i("ZZZ", downloaded + " => "+ total);
			
			if(percentage < 99){
				if(Constants.isNetworkConnected(getBaseContext())){
					Toast.makeText(getBaseContext(), "There is a problem with your connection.\nTrying again...", Toast.LENGTH_SHORT).show();
					new DownloadTask().execute();
				}else{
					finish();
				}
			}else{
				downloadOK = true;
				gotoMainPage();
			}
		}
    }
    
    
    @Override
   public void onBackPressed() {
 
        // set the flag to true so the next activity won't start up
        mIsBackButtonPressed = true;
        super.onBackPressed();
 
    }

}
